/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.grpc.server;

import com.hyts.grpc.base.server.AbstractGrpcServer;
import com.hyts.grpc.config.GrpcConfiguration;
import com.hyts.grpc.domain.GrpcConnecion;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @project-name:coffice-toolbox
 * @package-name:com.hyts.grpc.server
 * @author:LiBo/Alex
 * @create-date:2019-07-19 14:55
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description: simple level the grpc server
 */
@Slf4j
public class SimpleGrpcServer extends AbstractGrpcServer<GrpcConnecion> {


    public SimpleGrpcServer(List<BindableService> bindServiceCollection) {
        super(bindServiceCollection);
    }

    /**
     * @param param
     * @return
     */
    @Override
    public boolean start(GrpcConnecion param) {
        Objects.requireNonNull(param,"传入的连接池对象不允许为空!");
        param.setIp(Optional.ofNullable(param.getIp()).orElse(GrpcConfiguration.DEFAULT_SERVER_ADDRESS));
        param.setPort(Optional.ofNullable(param.getPort()).orElse(GrpcConfiguration.DEFAULT_SERVER_PORT));
        try {
            ServerBuilder serverBuilder = ServerBuilder.forPort(param.getPort());
            Optional.ofNullable(bindServiceCollection).ifPresent(coll->coll.parallelStream().
                    forEach(serverBuilder::addService));
            server = serverBuilder.build().start();
            server.awaitTermination();
        } catch (IOException | InterruptedException e) {
            log.error("启动GrpcServer服务失败!",e);
            return false;
        }finally {
            Runtime.getRuntime().addShutdownHook(new Thread(()->{
                if(stop()) {
                    log.info("开启后台监听Grpc服务关闭GC线程服务-服务进行关闭-因为JVM以及关闭");
                }else{
                    log.warn("服务关闭失败!-grpc后台线程gc");
                }
            }));
        }
        return true;
    }

    /**
     * stop the server grpc
     * @return
     */
    @Override
    public boolean stop() {
        try {
            Optional.ofNullable(server).ifPresent(Server::shutdown);
        } catch (Exception e) {
            log.error("关闭GrpcServer服务失败!",e);
            return false;
        }
        return true;
    }


    /**
     * await stop server grpc
     * @return
     */
    public boolean stopAwait(){
        try {
            Optional.ofNullable(server).ifPresent(server1 -> {
                try {
                    server1.awaitTermination();
                } catch (InterruptedException e) {
                    log.error("关闭GrpcServer服务失败!",e);
                }
            });
        } catch (Exception e) {
            log.error("关闭GrpcServer服务失败!",e);
            return false;
        }
        return true;
    }
}
